package com.niu.service.impl;

import com.niu.anno.MyFlag;
import com.niu.mapper.DeptMapper;
import com.niu.mapper.EmpMapper;
import com.niu.pojo.Dept;
import com.niu.pojo.DeptLog;
import com.niu.service.DeptLogService;
import com.niu.service.DeptService;
import com.niu.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
@Primary
public class DeptServiceImpl2 implements DeptService {

    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpService empService;

    @Autowired
    private DeptLogService deptLogService;

    @MyFlag
    @Override
    public List<Dept> getList() {
        return deptMapper.getAll();
    }

    @MyFlag
    @Transactional(rollbackFor = ParseException.class) // 开启事务
    @Override
    public int deletById(Integer deptId) throws ParseException {
        // 删除部门信息
        int i = deptMapper.deletById(deptId);

        // 出现运行时异常, 默认事务会回滚
        // int a = 1 / 0;

        // 删除部门对应的员工信息
        int j = empService.deleteByDeptId(deptId);

        // 记录日志
        deptLogService.insertLog(new DeptLog(null, LocalDateTime.now(), "删除" + i + " 个部门和" + j + " 个员工"));

        // 编译时异常, 不会事务回滚
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = format.parse("asfasfgkjshdf");

        return i;
    }

    @Override
    public int insertDept(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        return deptMapper.insertDept(dept);
    }

    @MyFlag
    @Override
    public Dept getById(Integer id) {
        return deptMapper.getById(id);
    }

    @Override
    public int updateById(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        return deptMapper.updateById(dept);
    }
}
